package controller

import (
	"context"
	"datum_user/dao"
	"datum_user/grpc"
	"datum_user/model"
	"datum_user/proto"
	"datum_user/utils"
	"encoding/hex"
	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {
	phone := c.PostForm("phone")
	password := c.PostForm("password")
	verifyId := c.PostForm("verify_id") //滑动验证码二次验证参数
	//校验滑动验证码
	if ok, err := utils.SecondVerify(verifyId); !ok && err != nil {
		ToJson(c, 201, err.Error(), nil)
		return
	}
	//对手机号进行Aes加密
	AesPhone, err := utils.EncyptogAES([]byte(phone))
	if err != nil {
		ToJson(c, 201, err.Error(), nil)
		return
	}
	//查询用户
	var user model.User
	dao.Db.Where("phone = ?", hex.EncodeToString(AesPhone)).First(&user)
	if user.Id == 0 { //id != 0 则存在
		ToJson(c, 201, "您还未注册，请先注册！", nil)
	} else {
		if user.Password != password {
			ToJson(c, 201, "帐号或密码错误！", nil)
		} else {
			//签发token
			req := proto.GetTokenRequest{Uid: uint32(user.Id)}
			res, err := grpc.GetTokenService().GetToken(context.Background(),&req)
			if err != nil {
				ToJson(c, 201, err.Error(), nil)
				return
			}
			ToJson(c, 200, "ok", map[string]interface{}{"user": user, "phone": phone, "token": res.Token})
		}
	}
}
